/*
 * 存储微信内容，统计各个用户发送的微信数量
 * 消息内容存mongodb
 * 多媒体文件存BOS
 */
var mongodb = require('./mongodb');
var bos = require('./bos');

var getLatestPost = function(callback) {
    // 读取最新的文章
    mongodb.db.collection('posts').find({}, {sort: {'_id': -1}, limit: 1}, function (err, cursor) {
        if (err) {
            console.warn(err.message);
        } else {
            cursor.toArray(callback);
        }
    });
};

var putMessage = function(message) {
    // 查找联系人
    mongodb.db.collection('contacts').findOneAndUpdate({FromUserName: message.FromUserName}, {$inc: {"TotalMessage": 1}}, {
        returnOriginal: false,
        upsert: true
    }, function (err, contact) {
        if (err) {
            console.warn(err.message);
        } else {
            console.dir(contact);
        }
    });

    // 记录信息
    mongodb.db.collection('messages').insertOne(message, function (err, message) {
        if (err) {
            console.warn(err.message);
        } else {
            console.dir(message);
        }
    });
};

var putMaterial = function(material) {
    console.log(material);
    // 保存素材
    mongodb.db.collection('materials').updateOne({media_id: material.material},
        {name: material.name}, {upsert: true, w: 1}, function (err, result) {
            if (err) {
                console.warn(err.message);
            } else {
                console.dir(result);
            }
        });
};

var putImage = function(picurl, object, callback) {
    bos.putObject(picurl, object, callback);
};

exports.getLatestPost = getLatestPost;
exports.putMaterial = putMaterial;
exports.putMessage = putMessage;
exports.putImage = putImage;